package com.fjwt.gz.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.db.entity.ActivityBlacklistEntity;
import com.fjwt.gz.service.mapper.ActivityBlacklistMapper;
import com.fjwt.gz.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 活动白名单（必定中设置好的奖项，但是实际获得的奖品，按照设定的中奖规则执行） 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class ActivityBlacklistService extends ServiceImpl<ActivityBlacklistMapper, ActivityBlacklistEntity> {
    @Autowired
    private ActivityBlacklistMapper activityBlacklistMapper;

    public List<ActivityBlacklistEntity> getActivityBlacklistEntity(Long activityId, Long redisOutTime) {
        // 参数校验
        if (activityId == null || redisOutTime == null || redisOutTime <= 0) {
            log.warn("活动ID或过期时间无效，activityId={}, redisOutTime={}", activityId, redisOutTime);
            return Collections.emptyList();
        }

        String activityBlacklistKey = buildRedisKey(activityId);

        // 从 Redis 获取数据
        List<ActivityBlacklistEntity> activityBlacklistEntities = null;
        try {
            activityBlacklistEntities = RedisUtil.getObject(activityBlacklistKey,
                    new TypeReference<List<ActivityBlacklistEntity>>() {});
        } catch (Exception e) {
            log.error("Redis 获取活动黑名单异常，key={}", activityBlacklistKey, e);
        }

        log.info("活动ID：{}，活动黑名单redis key:{}, redis中查询结果：{}", activityId, activityBlacklistKey, JsonUtils.toJson(activityBlacklistEntities));

        if (CollUtil.isNotEmpty(activityBlacklistEntities)) {
            return activityBlacklistEntities;
        }

        // 从数据库查询
        LambdaQueryWrapper<ActivityBlacklistEntity> gw = ActivityBlacklistEntity.gw();
        gw.eq(ActivityBlacklistEntity::getActivityId, activityId);
        activityBlacklistEntities = activityBlacklistMapper.selectList(gw);

        // 缓存空结果防止穿透
        if (CollUtil.isEmpty(activityBlacklistEntities)) {
            activityBlacklistEntities = Collections.emptyList();
            RedisUtil.set(activityBlacklistKey, activityBlacklistEntities, 5, TimeUnit.MINUTES); // 短时缓存
        } else {
            RedisUtil.set(activityBlacklistKey, activityBlacklistEntities, redisOutTime, TimeUnit.MILLISECONDS);
        }

        log.info("活动ID：{}，数据库查询活动黑名单结果：{}", activityId, activityBlacklistEntities);

        return activityBlacklistEntities;
    }

    private String buildRedisKey(Long activityId) {
        return String.format("%s%s:%s", Constants.REDIS_ACTIVITY.FILENAME, activityId, Constants.REDIS_ACTIVITY.ACTIVITY_BLACKLIST);
    }
}
